// packageI/knowledge/knowledgeDetail/knowledgeDetail.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    show: false,
    articleData: {},
    article: "",
    article_name: "",
    article_list: [],
    love_count: 0,//点赞人数
    love_member: [],//点赞人头像
    base: {},//知识库信息
    isStart:true,
    isEnd:true,
    isActivated:false,

    plugin: 'message-base',//message-base商城知识库，project-template供应链知识库
    catalogueProps: {},
    showLove: true,//是否显示点赞
    showBase: true//是否显示文章模块
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.initOption();
  },

  async initOption(){
    let api = new Map([
      ["message-base", {
        index: 'plugin.message-base.frontend.article.articleDetail',
        baseArticle: 'plugin.message-base.frontend.article.baseArticle',
        params: ()=> {
          return {article_id: this.options.id, visit_source: 2}
        },
        baseArticleParams:{base_id : this.options.bid},
        showLove: true,
        showBase: true,
        list: {
          label: "article_list",
          children: "article_name",
          content: 'article'
        },
        catalogueProps: {
          label: "article_name",
          children: "child",
        },
        callback:(res)=>{},
        getUD:(list)=>{
          // 计算当前目录是否到顶（上下章）
          this.setData({
            isStart: list[0]&&this.options.id == list[0].id,
            isEnd: this.getIsEnd(list,this.options.id)
          });
        },
        nextStartPage:({type})=>{
          if(type=="upPage"){
            if(this.data.isStart) return app.tips("文章已经到顶了");
            else this.upPage(this.data.article_list,this.data.article_list);
            return false;
          }
        },
        nextEndPage:({type})=>{
          if(type=="nextPage"){
            if(this.data.isEnd) return app.tips("文章已经到底了");
            let articleId = this.options.id;
            for (let i = 0; i < this.data.article_list.length; i++) {
              let item = this.data.article_list[i];
              if (item.id == articleId) {
                if (item.child.length>=1) {
                  this.toDetail(item.child[0].id);
                  return false;
                }else if(this.data.article_list[i+1]){
                  this.toDetail(this.data.article_list[i+1].id);
                  return false;
                }
                return true;
              }
              if(this.nextPage(item.child,articleId)){
                this.toDetail(this.data.article_list[i+1].id);
                return false;
              }
            }
          }
        },
      }
      ],
      ["project-template", {
        index: 'plugin.project-template.frontend.knowledge.articleDetatil',
        baseArticle: 'plugin.project-template.frontend.knowledge.knowledgeBaseCatalog',
        params: ()=> {
          return {id: this.options.id}
        },
        baseArticleParams:{id :this.options.bid},
        showLove: false,
        showBase: false,
        list: {
          label: "knowledgeBaseArticle",
          children: "title",
          content: 'content'
        },
        catalogueProps: {
          label: "title",
          children: "has_many_yz_supply_knowledge_base_article",
        },
        callback:(res)=>{},
        getUD:()=>{
          // 计算当前目录是否到顶（上下章）
          this.setData({
            isStart: this.data.articleData.previous_id?false:true,
            isEnd: this.data.articleData.next_id?false:true
          });
        },
        nextStartPage:({type})=>{
          if(type=="upPage"){
            if(!this.data.articleData.previous_id) return app.tips("文章已经到顶了");
            else this.toDetail(this.data.articleData.previous_id);
            return false;
          }
        },
        nextEndPage:({type})=>{
          if(type=="nextPage"){
            if(!this.data.articleData.next_id) return app.tips("文章已经到底了");
            this.toDetail(this.data.articleData.next_id);
          }
        },
      }
      ],
    ]);

    if(this.options.plu) {
      this.data.plugin = this.options.plu;
    }
    let _apiOption = api.get(this.data.plugin)
    this.setData({
      apiOption: _apiOption,
      catalogueProps: _apiOption.catalogueProps,
      showLove: _apiOption.showLove,
      showBase: _apiOption.showBase,
      isActivated: true,
      id: this.options.id
    })

    await this.getdata();
    this.getarticle_list();
  },
  getIsStart(list){
    // 计算是否到顶
    this.data.apiOption.getUD(list);
  },
  getIsEnd(list,id){
    if(list && list[list.length-1]){
      let child = list[list.length-1].child;
      if(child&&child.length>0){
        return this.getIsEnd(child,id);
      }
      return list[list.length-1].id == id;
    }
    return true;
  },
  treeTap(e){
    let {id} = e.detail.item;
    wx.redirectTo({
      url: `/packageI/knowledge/knowledgeDetail/knowledgeDetail?id=${id}&bid=${this.options.bid}&plu=${this.data.plugin}`
    });
  },
  toDetail(articleId){
    let base_id = this.options.bid;
    wx.redirectTo({
      url: `/packageI/knowledge/knowledgeDetail/knowledgeDetail?id=${articleId}&bid=${base_id}&plu=${this.data.plugin}`
    });
  },
  nextPage(list,articleId){
    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      if (item.id == articleId) {
        if (item.child.length>=1) {
          this.toDetail(item.child[0].id);
          return false
        }else if(list[i+1]){
          this.toDetail(list[i+1].id);
          return false
        }
        return true;
      }
      if (this.nextPage(item.child,articleId)) {
        if (list[i+1]) {
          this.toDetail(list[i+1].id);
          return false;
        }else return true;
      };
    }
  },
  upPage(list,plist,pindex){
    let articleId = this.options.id;
    for (let i = 0; i < list.length; i++) {
      let item = list[i];
      if (item.id == articleId) {
        let id = i<=0?plist[pindex].id:list[i-1].id;
        this.toDetail(id);
        return false;
      }
      this.upPage(item.child,list,i)
    }
  },
  operationPage(e){
    let type = e.target.dataset.type||e.currentTarget.dataset.type;
    if (this.data.article_list&&this.data.article_list.length>0) {
      if(type=="upPage"){
        // 上一章
        this.data.apiOption.nextStartPage({type: type});
      }
      if(type=="nextPage"){
        // 下一章
        this.data.apiOption.nextEndPage({type: type});
      }
    }
  },
  async getdata() {
    if(this.options.id && this.options.id == -1) {
      wx.redirectTo({
        url: `/packageI/knowledge/knowledgeList/knowledgeList?bid=${this.options.bid}&plu=${this.data.plugin}`
      });
      return;
    }

    let urlStr = app.getNetAddresss(this.data.apiOption.index);
    app._postNetWork({
      url: urlStr,
      data: this.data.apiOption.params(),
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          if(res.data.article) {
            try {
              this.data.article = decodeURIComponent(res.data.article[this.data.apiOption.list.content]);
            }catch (e) {
              this.data.article = res.data.article[this.data.apiOption.list.content];
            }
            this.data.article_name = res.data.article[this.data.apiOption.list.children];
            wx.setNavigationBarTitle({
              title: this.data.article_name || '知识库详情'
            })
          }

          this.setData({
            article: this.data.article,
            articleData: res.data,
            love_count: res.data.love_count,
            love_member: res.data.love_member,
            base: res.data.base || {},
          })
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  getarticle_list(){
    // let {knowledge} = this.$store.state;
    // let base_id = this.$route.query.base_id;
    // if (knowledge.baseArticle&&knowledge.base_id==base_id) {
    //   this.article_list = knowledge.baseArticle.data[this.apiOption.list.label].filter(r => {
    //     return r[this.apiOption.list.children] != "";
    //   });
    //   this.getIsStart(this.article_list);
    //   return true;
    // }
    this.showtime({target:{dataset:{show: false}}});
  },
  showtime(e) {
    let show = false;
    try {
      show = e.target.dataset.show||e.currentTarget.dataset.show
    } catch (error) {
      
    }
    if (this.data.article_list&&this.data.article_list.length>0) {
      this.setData({show: show})
      return false;
    }
    let urlStr = app.getNetAddresss(this.data.apiOption.baseArticle);
    app._postNetWork({
      url: urlStr,
      data: this.data.apiOption.baseArticleParams,
      success: (resdata) => {
        let res = resdata.data;
        if (res.result == 1) {
          this.data.article_list = res.data[this.data.apiOption.list.label].filter(r => {
            return r[this.data.apiOption.list.children] != "";
          });
          this.setData({
            article_list: this.data.article_list
          })
          this.getIsStart(this.data.article_list);
          this.setData({ show: show })
        } else {
          wx.showToast({
            icon: "none",
            title: res.msg,
            duration: 1000,
          });
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  clicklove() {
    let urlStr = app.getNetAddresss('plugin.message-base.frontend.article.articleLove');
    app._postNetWork({
      url: urlStr,
      data: {
        article_id: this.options.id,
        is_love: this.data.articleData.is_love ? 0 : 1
      },
      success: (resdata) => {
        let res = resdata.data;
        wx.showToast({
          icon: "none",
          title: res.msg,
          duration: 1000,
        });
        if (res.result == 1) {
          this.setData({
            ['articleData.is_love']: !this.data.articleData.is_love,
            love_count: this.data.articleData.is_love ? this.data.love_count ++ : this.data.love_count --
          })
          this.getdata();
        }
      },
      fail: (res) => {
        console.log(res);
      },
    });
  },
  toBack(){
    wx.navigateBack({
      delta: 1,
      fail: () => {
        this.toHome();
      }
    })
  },
  toHome(){
    wx.redirectTo({
      url: `/packageI/knowledge/knowledgeIndex/knowledgeIndex?plu=${this.data.plugin}`
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({isActivated: false})
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let value = wx.getStorageSync("yz_uid");
    let mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: '/packageI/knowledge/knowledgeDetail/knowledgeDetail?plu='+ this.options.plu + '&bid='+  this.options.bid + '&id='+  this.options.id + '&mid=' + mid
    }
  }
})